/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import qs from 'qs'
import router from '@/router'
import { getBrowserInfo } from '@/util/util'
import { getToken, getRefreshToken, removeRefreshToken, removeToken, setRefreshToken, setToken } from '@/util/auth'
import { Message, MessageBox } from 'element-ui'
// import { Base64 } from 'js-base64'
// import { DEFAULT_ENTRYPOINT } from '../config/entrypoint'

const DEFAULT_ENTRYPOINT = window.service.host

let REFRESHER = null

// 默认超时时间
axios.defaults.timeout = 100000
// 返回其他状态码
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500
}
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true

// http request拦截
axios.interceptors.request.use(config => {
  // 检测请求路径里不包含/js/  时，进行路径拼接
  if (typeof (config.url) === 'string' && config.url.indexOf('/js/') < 0 && config.url.indexOf(DEFAULT_ENTRYPOINT) < 0) {
    config.url = DEFAULT_ENTRYPOINT + config.url
  } else if (typeof (config.url) === 'object') {
    config.url = DEFAULT_ENTRYPOINT + config.url.url
  }
  const meta = (config.meta || {})
  const isToken = meta.isToken === false
  config.headers['X-Terminal-Type'] = getBrowserInfo().browser // 浏览器
  config.headers['X-Terminal-Version'] = getBrowserInfo().ver // 浏览器版本
  // 让每个请求携带token
  if (!isToken) {
    config.headers.Authorization = 'bearer ' + getToken()
  } else {
    config.headers.Authorization = 'Basic eXV5aS1hZG1pbjoxMjM0NTY='
  }
  // headers中配置text请求
  if (config.text === true) {
    config.headers['Content-Type'] = 'text/plain'
  }
  return config
}, error => {
  return Promise.reject(error)
})
// http response 拦截
axios.interceptors.response.use(res => {
  // 获取状态码
  const status = res.status
  const code = res.data.code
  const message = res.data.message || '未知错误'
  // 如果是401则进行token的刷新
  if (res.statusText === 'OK' && (code === 200 || code === undefined)) {
    return Promise.resolve(res)
  }
  if (status === 401) {
    return refreshToken(res.config)
  }
  if (status > 299 || code > 299 || code < 200) {
    // 如果请求为非200否者默认统一处理
    Message({
      message: message,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  }
}, err => {
  console.log(err)
})

export default axios

const refreshToken = (config) => {
  if (REFRESHER === null) {
    REFRESHER = axios({
      url: '/yuyi-auth/api/oauth/token',
      method: 'post',
      meta: {
        isToken: false,
        requestType: 'refresh'
      },
      data: qs.stringify({
        username: '',
        password: '',
        grant_type: 'refresh_token',
        captchaCode: '',
        captchaId: '',
        refresh_token: getRefreshToken()
      })
    })
  }
  return REFRESHER.then((res) => {
    if (res.data.data.access_token) {
      REFRESHER = null
      setToken(res.data.data.access_token)
      setRefreshToken(res.data.data.refresh_token)
      return axios(config)
    } else {
      return Promise.reject(new Error(res.data.message))
    }
  }).catch((error) => {
    MessageBox.alert('登录已过期，请重新登录', '提示', {
      confirmButtonText: '确定',
      type: 'warning',
      callback: action => {
        removeToken()
        removeRefreshToken()
        router.replace('/login')
      }
    })
    REFRESHER = null
    return Promise.reject(error)
  })
}
